<template>
  <div class="friendContainer">
    <div class="header">
      <div class="title">
        <div class="label" title="添加好友">Add</div>
      </div>
    </div>

    <div class="divide"></div>

    <!-- 添加好友 -->
    <AddFriend :changeRefreshSignal="changeRefreshSignal" />

    <div class="divide"></div>

    <div class="header">
      <div class="title">
        <div class="label" title="关注列表">Follow</div>

        <el-icon
          size="24"
          :color="buttonColor"
          title="切换我的关注面板"
          @click="toggleExtendFollowBox"
        >
          <Sort />
        </el-icon>
      </div>
    </div>

    <div class="divide"></div>

    <!-- 关注盒子 -->
    <FollowBox
      :toggle="extendFollowBox"
      :refreshSignal="refreshSignal"
      :changeRefreshSignal="changeRefreshSignal"
    />

    <div class="divide"></div>

    <div class="header">
      <div class="title">
        <div class="label" title="粉丝列表">Fans</div>

        <el-icon
          size="24"
          :color="buttonColor"
          title="切换关注我的面板"
          @click="toggleExtendFansBox"
        >
          <Sort />
        </el-icon>
      </div>
    </div>

    <div class="divide"></div>

    <!-- 粉丝盒子 -->
    <FansBox :toggle="extendFansBox" :refreshSignal="refreshSignal" />

    <div class="divide"></div>
  </div>
</template>

<script lang="tsx" setup>
import { defineComponent, onMounted, ref, watch } from 'vue'
import { useThemeStore } from '@/features/store/store'
import { storeToRefs } from 'pinia'
import {
  Sort,
  Avatar,
  CircleCheckFilled,
  Setting,
  Tools,
  DeleteFilled,
  Switch,
  Reading,
  Clock,
  Management,
  Collection,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import {
  searchFriendApi,
  addFriendApi,
  getFriendListApi,
  deleteFriendApi,
} from '@/request/api/friends'
import {
  getShareProjectDetailApi,
  addShareProjectApi,
  deleteShareProjectApi,
  getFriendShareListDetailApi,
} from '@/request/api/shareProject'
import styles from './friend.module.less'
import LoadingClass from '@/utils/utilClass/Loading'
import PaginationBar from '@/components/PaginationBar.vue'
import { sourceUrl } from '@/config/baseConfig'

//
// 按钮颜色
const { buttonColor } = storeToRefs(useThemeStore())
// 是否更新数据信号
const refreshSignal = ref<string>('')
// 更新信号
const changeRefreshSignal = () => (refreshSignal.value = new Date() + '')

//
// 添加好友
const AddFriend = defineComponent({
  props: {
    changeRefreshSignal: { type: Function, defaule: '' },
  },
  setup(props) {
    const { buttonColor } = storeToRefs(useThemeStore())

    // 添加好友栏
    const addHeight = ref<'130px' | '28px'>('28px')
    const addOverflow = ref<'hidden' | ''>('hidden')
    const addFreindBar = ref<true | false>(false)

    // 切换添加栏
    const toggleCreate = (): void => {
      if (addFreindBar.value) {
        addFreindBar.value = false
        addHeight.value = '28px'
        addOverflow.value = 'hidden'
      } else {
        addHeight.value = '130px'
        addOverflow.value = ''
        setTimeout(() => (addFreindBar.value = true), 100)
      }
    }

    const account = ref<string>('')
    const nickname = ref<string>('')
    const avatar = ref<string>('')
    // 查询的用户是否已经添加为好友了
    const isFreind = ref<boolean>(false)

    const ClassLoading1 = new LoadingClass()
    // 用户信息卡片
    const visible = ref<boolean>(false)
    // 输入框中的值
    const inputAccount = ref<string>('')

    // 查询好友账号
    const searchFriend = async () => {
      if (!inputAccount.value) return ClassLoading1.setTips('参数不能为空！')

      ClassLoading1.loading.value = true
      const res = await searchFriendApi(inputAccount.value)
      ClassLoading1.loading.value = false

      if (res.code !== 200) return ClassLoading1.setTips('查询失败！')

      ClassLoading1.setTips('查询成功！')
      const { account: acc, nickname: n, avatar: a } = res.data.master
      isFreind.value = res.data.isAdd
      account.value = acc
      nickname.value = n
      avatar.value = sourceUrl + a
      visible.value = true
    }

    const ClassLoading2 = new LoadingClass()

    // 添加好友
    const addFriend = async () => {
      if (!account.value) return

      ClassLoading2.loading.value = true
      const res = await addFriendApi(account.value)
      ClassLoading2.loading.value = false

      if (res.code !== 200) return ClassLoading2.setTips('添加失败！')
      ClassLoading2.setTips('添加成功！')
      isFreind.value = true
      props.changeRefreshSignal()
    }

    return () => (
      <div
        class={styles.addFreind}
        style={{ height: addHeight.value, overflow: addOverflow.value }}
      >
        <div class={styles.tipsTxt} v-show={!addFreindBar.value}>
          添加新好友
        </div>

        {/* 搜索部分 */}
        <div class={styles.searchBar} v-show={addFreindBar.value}>
          {/* 搜索框 */}
          <div class={styles.searchInput}>
            <div class={styles.label}>好友账号：</div>
            <div>
              <el-input
                v-model={inputAccount.value}
                clearable
                placeholder="Please input friend account"
              />
            </div>
            <div class={styles.btn}>
              <el-button
                plain
                color={buttonColor.value}
                loading={ClassLoading1.loading.value}
                onClick={searchFriend}
              >
                查找
              </el-button>

              <div class={styles.tips}>{ClassLoading1.resultTips.value}</div>
            </div>
          </div>

          {/* 查找到的用户信息名片 */}
          <div class={styles.userCard} v-show={visible.value}>
            <el-avatar size={60} src={avatar.value} />
            <div class={styles.userInfo}>
              <div class={styles.account}>{account.value}</div>
              <div class={styles.nickname}>
                <el-icon>
                  <Avatar />
                </el-icon>
                &nbsp; {nickname.value}
              </div>
            </div>
            <div class={styles.btn}>
              <el-icon
                v-show={isFreind.value}
                size="28"
                color="#67C23A"
                title="已添加为好友"
              >
                <CircleCheckFilled />
              </el-icon>

              <el-button
                v-show={!isFreind.value}
                plain
                color={buttonColor.value}
                loading={ClassLoading2.loading.value}
                onClick={addFriend}
              >
                添加
              </el-button>
              <div class={styles.tips}>{ClassLoading2.resultTips.value}</div>
            </div>
          </div>
        </div>

        {/* 切换按钮 */}
        <div class={styles.toggle}>
          <div onClick={toggleCreate}>
            <el-icon size="24" color={buttonColor.value} title="切换面板">
              <Sort />
            </el-icon>
          </div>
        </div>
      </div>
    )
  },
})

//
// 是否展开我的关注列表
const extendFollowBox = ref<boolean>()
const toggleExtendFollowBox = () =>
  (extendFollowBox.value = !extendFollowBox.value)
//
// 关注
const FollowBox = defineComponent({
  props: {
    toggle: { type: Boolean, defaule: false },
    refreshSignal: { type: String, defaule: '' },
    changeRefreshSignal: { type: Function, defaule: '' },
  },
  setup(props) {
    onMounted(() => {
      getFriendList()
    })
    watch(
      () => props.toggle,
      () => toggleFollow()
    )
    // 粉丝列表相关信息
    const followHeight = ref<'auto' | '28px'>('auto')
    const followOverflow = ref<'' | 'hidden'>('')
    const followFreindBox = ref<true | false>(true)
    // 切换
    const toggleFollow = (): void => {
      if (followFreindBox.value) {
        followFreindBox.value = false
        followHeight.value = '28px'
        followOverflow.value = 'hidden'
      } else {
        followHeight.value = 'auto'
        followOverflow.value = ''
        setTimeout(() => (followFreindBox.value = true), 100)
        getFriendList()
      }
    }

    watch(
      () => props.refreshSignal,
      () => getFriendList()
    )

    const size = ref<number>(12)
    const page = ref<number>(1)
    const total = ref<number>(0)
    const pageChange = (p: number) => {
      page.value = p
      getFriendList()
    }
    const sizeChange = (s: number) => {
      size.value = s
      getFriendList()
    }

    // 关注的列表
    const followList = ref<getFriendResultItf[]>()
    // 获取我关注的人
    const getFriendList = async () => {
      const res = await getFriendListApi({
        type: 0,
        page: page.value,
        pageSize: size.value,
      })
      if (res.code != 200) return (followList.value = [])
      followList.value = res.data.records
    }

    // 当前正在操作的卡片id
    const settingCardId = ref<string>('')
    const setSettingCardId = (id: string) => (settingCardId.value = id)

    // 用户信息部分
    const UserInfo = defineComponent({
      props: {
        id: { type: String, defaule: '' },
        mutual: { type: Boolean, defaule: '' },
        avatar: { type: String, defaule: '' },
        nickname: { type: String, defaule: '' },
        addTime: { type: String, defaule: '' },

        settingCardId: { type: String, defaule: '' },
        setSettingCardId: { type: Function, defaule: '' },
        changeRefreshSignal: { type: Function, defaule: '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())

        //
        // 删除好友
        const deleteFriend = async () => {
          const res = await deleteFriendApi(props.id)
          if (res.code !== 200) return ElMessage.error('删除失败！')
          props.changeRefreshSignal()
        }

        return () => (
          <div class={styles.followInfo}>
            <el-avatar size={54} src={sourceUrl + props.avatar} />

            <div class={styles.info}>
              <div class={styles.nickname} title={props.nickname}>
                {' '}
                {props.nickname}
              </div>

              <div class={styles.tools}>
                <el-icon
                  v-show={props.settingCardId !== props.id}
                  size="22"
                  color={buttonColor.value}
                  onClick={() => props.setSettingCardId(props.id)}
                  title="设置"
                >
                  <Setting />
                </el-icon>

                <el-icon
                  v-show={props.settingCardId === props.id}
                  title="设置"
                  size="22"
                  color={buttonColor.value}
                  onClick={() => props.setSettingCardId('')}
                >
                  <Tools />
                </el-icon>

                <el-icon
                  size={20}
                  title={'添加时间：' + props.addTime}
                  color={buttonColor.value}
                >
                  <Clock />
                </el-icon>

                <el-icon
                  v-show={props.mutual}
                  size={20}
                  title="相互关注"
                  color={buttonColor.value}
                >
                  <Switch />
                </el-icon>

                <el-popconfirm
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  title="确定删除吗？"
                  onConfirm={deleteFriend}
                  v-slots={{
                    reference: () => (
                      <el-icon
                        v-show={props.settingCardId !== props.id}
                        size="22"
                        color={buttonColor.value}
                        title="删除好友"
                      >
                        <DeleteFilled />
                      </el-icon>
                    ),
                  }}
                ></el-popconfirm>
              </div>
            </div>
          </div>
        )
      },
    })

    // 编辑分享列表
    const EditShareProject = defineComponent({
      props: {
        settingCardId: { type: String, default: '' },
        friendId: { type: String, default: '' },
      },
      setup(props) {
        // 添加分享项目按钮部分
        const BtnIcon = defineComponent({
          props: {
            isShare: { type: Boolean, default: false },
            addProject: { type: Function, default: false },
            deleteProject: { type: Function, default: false },
          },
          setup(props) {
            return () => (
              <>
                <el-icon
                  v-show={props.isShare}
                  size="24"
                  color="#67C23A"
                  onClick={props.deleteProject}
                  title="已分享，点击删除"
                >
                  <CircleCheckFilled />
                </el-icon>
                <el-icon
                  v-show={!props.isShare}
                  size="24"
                  color="#909399"
                  onClick={props.addProject}
                  title="未分享，点击添加"
                >
                  <CircleCheckFilled />
                </el-icon>
              </>
            )
          },
        })

        watch(
          () => props.settingCardId,
          () => {
            if (props.settingCardId === props.friendId) getShareProjectDetail()
            else projectList.value = []
          }
        )

        const classLoading = new LoadingClass()

        // 分享给好友的项目详情列表
        const projectList = ref<getShareProjectDetailItf[]>([])

        // 获取分享给好友的项目详情
        const getShareProjectDetail = async () => {
          const res = await getShareProjectDetailApi(props.friendId)
          if (res.code !== 200) {
            classLoading.setTips('获取分享给好友的项目详情失败！', 5000)
            return (projectList.value = [])
          }
          projectList.value = res.data
        }

        // 为好友添加分享项目
        const addShareProject = async (valId: string) => {
          const data: addShareProjectItf = {
            friendId: props.friendId,
            projectId: valId,
          }
          classLoading.setTips('请求发送中。。。')
          const res = await addShareProjectApi(data)
          if (res.code !== 200) return classLoading.setTips('添加失败！')
          getShareProjectDetail()
          classLoading.setTips('添加成功！')
        }

        // 为好友删除分享项目
        const deleteShareProject = async (valId: string) => {
          const data: deleteShareProjectItf = {
            friendId: props.friendId,
            projectId: valId,
          }
          classLoading.setTips('请求发送中。。。')
          const res = await deleteShareProjectApi(data)
          if (res.code !== 200) return classLoading.setTips('删除失败！')
          classLoading.setTips('删除成功！')
          getShareProjectDetail()
        }

        return () => (
          <div class={styles.shareDetail}>
            <div class={styles.tips}>
              操作提示： <div>{classLoading.resultTips.value}</div>
            </div>

            <div class={styles.projectList}>
              {projectList.value.map((item) => {
                const theId = item.projectId
                return (
                  <div class={styles.project}>
                    <div>{item.title}</div>

                    <el-button
                      size="small"
                      circle
                      v-slots={{
                        icon: () => (
                          <BtnIcon
                            isShare={item.isShare}
                            addProject={() => addShareProject(theId)}
                            deleteProject={() => deleteShareProject(theId)}
                          />
                        ),
                      }}
                    />
                  </div>
                )
              })}
            </div>
          </div>
        )
      },
    })

    return () => (
      <div
        class={styles.followBox}
        style={{ height: followHeight.value, overflow: followOverflow.value }}
      >
        <div class={styles.tipsTxt} v-show={!followFreindBox.value}>
          我关注的人
        </div>

        <div class={styles.followCards} v-show={followFreindBox.value}>
          {followList.value?.map((item) => {
            return (
              <div
                class={styles.card}
                id={
                  settingCardId.value === item.friendId
                    ? styles.settingCard
                    : ''
                }
                key={item.friendId}
              >
                {/* 用户信息 */}
                <UserInfo
                  id={item.friendId}
                  mutual={item.mutual}
                  avatar={item.friendAvatar}
                  nickname={item.friendNickname}
                  addTime={item.createTime}
                  settingCardId={settingCardId.value}
                  setSettingCardId={setSettingCardId}
                  changeRefreshSignal={props.changeRefreshSignal}
                />

                <div
                  class={styles.divide}
                  v-show={settingCardId.value === item.friendId}
                ></div>

                {/* 编辑分享项目部分 */}
                <EditShareProject
                  v-show={settingCardId.value === item.friendId}
                  settingCardId={settingCardId.value}
                  friendId={item.friendId}
                />
              </div>
            )
          })}
        </div>

        {/* 分页栏 */}
        <PaginationBar
          size={size.value}
          page={page.value}
          total={total.value}
          sizeChange={sizeChange}
          currentChange={pageChange}
        />
      </div>
    )
  },
})

//
// 是否展开我的关注列表
const extendFansBox = ref<boolean>()
const toggleExtendFansBox = () => (extendFansBox.value = !extendFansBox.value)
//
// 粉丝
const FansBox = defineComponent({
  props: {
    toggle: { type: Boolean, defaule: false },
    refreshSignal: { type: String, defaule: '' },
  },
  setup(props) {
    onMounted(() => {
      getFansList()
    })
    watch(
      () => props.toggle,
      () => toggleFollow()
    )
    // 添加好友栏
    const fansHeight = ref<'auto' | '28px'>('auto')
    const fansOverflow = ref<'' | 'hidden'>('')
    const fansFreindBox = ref<true | false>(true)
    // 切换
    const toggleFollow = (): void => {
      if (fansFreindBox.value) {
        fansFreindBox.value = false
        fansHeight.value = '28px'
        fansOverflow.value = 'hidden'
      } else {
        fansHeight.value = 'auto'
        fansOverflow.value = ''
        setTimeout(() => (fansFreindBox.value = true), 100)
        getFansList()
      }
    }

    watch(
      () => props.refreshSignal,
      () => getFansList()
    )

    const size = ref<number>(12)
    const page = ref<number>(1)
    const total = ref<number>(0)
    const pageChange = (p: number) => {
      page.value = p
      getFansList()
    }
    const sizeChange = (s: number) => {
      size.value = s
      getFansList()
    }

    // 关注的列表
    const fansList = ref<getFriendResultItf[]>()
    // 获取关注我的人
    const getFansList = async () => {
      const res = await getFriendListApi({
        type: 1,
        page: page.value,
        pageSize: size.value,
      })
      if (res.code !== 200) return (fansList.value = [])
      fansList.value = res.data.records
      total.value = res.data.total
    }

    // 当前正在操作的卡片id
    const settingCardId = ref<string>('')
    const setSettingCardId = (id: string) => (settingCardId.value = id)

    // 用户信息部分
    const UserInfo = defineComponent({
      props: {
        id: { type: String, defaule: '' },
        mutual: { type: Boolean, defaule: '' },
        avatar: { type: String, defaule: '' },
        nickname: { type: String, defaule: '' },
        addTime: { type: String, defaule: '' },
        settingCardId: { type: String, defaule: '' },
        setSettingCardId: { type: Function, defaule: '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())

        return () => (
          <div class={styles.fansInfo}>
            <el-avatar size={54} src={sourceUrl + props.avatar} />

            <div class={styles.info}>
              <div class={styles.nickname} title={props.nickname}>
                {props.nickname}
              </div>

              <div class={styles.tools}>
                <el-icon
                  size={20}
                  title={'添加时间：' + props.addTime}
                  color={buttonColor.value}
                >
                  <Clock />
                </el-icon>

                <el-icon
                  v-show={props.mutual}
                  size={20}
                  title="相互关注"
                  color={buttonColor.value}
                >
                  <Switch />
                </el-icon>

                <el-icon
                  v-show={props.settingCardId !== props.id}
                  size="22"
                  color={buttonColor.value}
                  onClick={() => props.setSettingCardId(props.id)}
                  title="阅读列表"
                >
                  <Collection />
                </el-icon>

                <el-icon
                  v-show={props.settingCardId === props.id}
                  title="阅读列表"
                  size="22"
                  color={buttonColor.value}
                  onClick={() => props.setSettingCardId('')}
                >
                  <Management />
                </el-icon>
              </div>
            </div>
          </div>
        )
      },
    })

    // 分享列表
    const ShareProject = defineComponent({
      props: {
        friendId: { type: String, default: '' },
        settingCardId: { type: String, default: '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())

        watch(
          () => props.settingCardId,
          () => {
            if (props.settingCardId === props.friendId) getFriendShareDetail()
            else projectList.value = []
          }
        )

        // 打开阅读窗口
        const openReadingWindow = (projectId: string, projectName: string) =>
          (window as any).readingWindow.openWindow({
            projectId: projectId,
            projectTitle: projectName,
            token: window.localStorage.getItem('token'),
            type: 'shareProject',
          })

        // 分享给好友的项目详情列表
        const projectList = ref<getFriendShareDetailItf[]>([])

        // 获取好友分享的项目
        const getFriendShareDetail = async () => {
          const res = await getFriendShareListDetailApi(props.friendId)
          if (res.code !== 200) return (projectList.value = [])
          projectList.value = res.data
        }

        return () => (
          <div class={styles.shareDetail}>
            {projectList.value.map((item) => {
              return (
                <div class={styles.project}>
                  <div>{item.projectTitle}</div>

                  <div
                    onClick={() =>
                      openReadingWindow(item.projectId, item.projectTitle)
                    }
                  >
                    <el-icon
                      size={24}
                      title="查看此项目收获笔记"
                      color={buttonColor.value}
                    >
                      <Reading />
                    </el-icon>
                  </div>
                </div>
              )
            })}
          </div>
        )
      },
    })

    return () => (
      <div
        class={styles.fansBox}
        style={{ height: fansHeight.value, overflow: fansOverflow.value }}
      >
        <div class={styles.tipsTxt} v-show={!fansFreindBox.value}>
          关注我的人
        </div>

        <div class={styles.fansCards} v-show={fansFreindBox.value}>
          {fansList.value?.map((item) => {
            return (
              <div
                class={styles.card}
                id={
                  settingCardId.value === item.masterId
                    ? styles.settingCard
                    : ''
                }
                key={item.masterId}
              >
                {/* 用户信息 */}
                <UserInfo
                  id={item.masterId}
                  mutual={item.mutual}
                  avatar={item.masterAvatar}
                  nickname={item.masterNickname}
                  addTime={item.createTime}
                  settingCardId={settingCardId.value}
                  setSettingCardId={setSettingCardId}
                />

                <div
                  class={styles.divide}
                  v-show={settingCardId.value === item.masterId}
                ></div>

                {/* 好友分享的项目 */}
                <ShareProject
                  v-show={settingCardId.value === item.masterId}
                  friendId={item.masterId}
                  settingCardId={settingCardId.value}
                />
              </div>
            )
          })}
        </div>

        {/* 分页栏 */}
        <PaginationBar
          size={size.value}
          page={page.value}
          total={total.value}
          sizeChange={sizeChange}
          currentChange={pageChange}
        />
      </div>
    )
  },
})
</script>

<style lang="less" scoped>
@fontstyle: comic Sans MS, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
  Oxygen, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;

.friendContainer {
  width: calc(100% - 24px);
  min-height: 100%;
  padding: 12px;

  > .header {
    width: 100%;
    transition: 0.2s;

    > .title {
      font-family: @fontstyle;
      font-size: 18px;
      font-weight: bold;
      color: var(--theme-active-label);
      user-select: none;
      display: flex;
      //  align-items: center;
      > .label {
        width: 200px;
      }

      > .el-icon {
        &:hover {
          scale: 1.2;
          cursor: pointer;
        }
      }
    }
  }

  > .divide {
    height: 2px;
    width: 100%;
    background-color: var(--theme-header);
    margin-top: 10px;
    margin-bottom: 10px;
  }
}
</style>
